#!/usr/bin/env python
#
# Copyright 2008 Richard J. Bell. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

""" Base request handler """

# Python Imports
import os

# Google App Engine Imports
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template

class BaseRequestHandler(webapp.RequestHandler):
  """BaseRequestHandler extends webapp.Request handler
     It defines the generate method, which renders a Django template
     in response to a web request
  """
  def generate(self, template_name, template_values={}):
    from main import _DEBUG
    """Generate renders an HTML template along with values passed to that 
       template
       Args:
         template_name: A string that represents the name of the HTML 
                        template
         template_values: A dictionary that associates objects with a string
           assigned to that object to call in the HTML template.  The 
           defualt is an empty dictionary.
    """
    # We check if there is a current user and generate a login or logout URL
    user = users.get_current_user()
    
    log_in_url = users.create_login_url(self.request.path)
    log_out_url = users.create_logout_url('/wikiview/StartPage')

    # We'll display the user name if available and the URL on all pages
    values = {'user': user, 
              'log_in_url': log_in_url, 
              'log_out_url': log_out_url, 
              'admin': users.is_current_user_admin()}
    # add the template values
    values.update(template_values)

    # Construct the path to the template
    directory = os.path.dirname(__file__) + '/..'
    path = os.path.join(directory, 'templates', template_name)

    # Respond to the request by rendering the template
    self.response.out.write(template.render(path, values, debug=_DEBUG))

    